package com.essence.common.model.parser;

import com.essence.common.model.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ByteBufParser implements InfoObjectParser {
    public static final Logger LOG = LoggerFactory.getLogger(ByteBufParser.class);

    public void parse(Packet packet, byte[] infoObjectBytes) {
        if (packet.getVsq().getNum() * infoObjectLength() != infoObjectBytes.length) {
            LOG.error("\nTI：{} 出现解析错误\n ASDU:{}",  packet.getTieIdentification().getDescription(),packet.getAsduBytes());
            throw new DataLengthException(packet.getVsq().getNum() * infoObjectLength(), infoObjectBytes.length);
        }
        ByteBuf buf = Unpooled.buffer(infoObjectBytes.length);
        try {
            buf.writeBytes(infoObjectBytes);
            parse(packet, buf);
        } finally {
            buf.release();
        }
    }

    abstract void parse(Packet packet, ByteBuf buf);

    abstract int infoObjectLength();
}
